from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, Enum
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from config import db_config, default_data
from models import UserRole

# 数据库配置
DATABASE_URL = db_config.get_database_url()

print(DATABASE_URL)

# 创建引擎
engine = create_engine(
    DATABASE_URL, 
    echo=False,
    pool_pre_ping=True
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# 用户数据库模型
class DBUser(Base):
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    name = Column(String(100), nullable=False)
    password = Column(String(100), nullable=False)
    role = Column(Enum(UserRole), default=UserRole.USER)
    created_at = Column(DateTime, default=datetime.utcnow)

# 商品数据库模型
class DBProduct(Base):
    __tablename__ = "shop_manager"
    
    id = Column(Integer, primary_key=True, index=True)
    product_name = Column(String(100), nullable=False)
    price = Column(Float, nullable=False)
    category = Column(String(50), nullable=False)
    stock = Column(Integer, nullable=False, default=0)
    sales = Column(Integer, nullable=False, default=0)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def init_db():
    print("开始初始化数据库...")
    print(f"当前数据库类型: MySQL")
    print(f"数据库URL: {DATABASE_URL}")
    
    try:
        Base.metadata.create_all(bind=engine)
        print("数据库表结构检查/创建完成")
        
        db = SessionLocal()
        try:
            # 管理员用户
            admin_user = db.query(DBUser).filter(DBUser.username == default_data.DEFAULT_ADMIN_USERNAME).first()
            if not admin_user:
                print("创建默认管理员用户...")
                admin_user = DBUser(
                    username=default_data.DEFAULT_ADMIN_USERNAME,
                    name=default_data.DEFAULT_ADMIN_NAME,
                    password=default_data.DEFAULT_ADMIN_PASSWORD,
                    role=UserRole.ADMIN
                )
                db.add(admin_user)
                print(f"管理员用户创建完成 (用户名: {default_data.DEFAULT_ADMIN_USERNAME}, 密码: {default_data.DEFAULT_ADMIN_PASSWORD})")
            else:
                print("管理员用户已存在")
            
            # 普通用户
            normal_user = db.query(DBUser).filter(DBUser.username == default_data.DEFAULT_USER_USERNAME).first()
            if not normal_user:
                print("创建默认普通用户...")
                normal_user = DBUser(
                    username=default_data.DEFAULT_USER_USERNAME,
                    name=default_data.DEFAULT_USER_NAME,
                    password=default_data.DEFAULT_USER_PASSWORD,
                    role=UserRole.USER
                )
                db.add(normal_user)
                print(f"普通用户创建完成 (用户名: {default_data.DEFAULT_USER_USERNAME}, 密码: {default_data.DEFAULT_USER_PASSWORD})")
            else:
                print("普通用户已存在")
            
            db.commit()
            
            # 创建示例商品数据
            create_sample_product_data(db)
            
            print("数据库初始化完成！")
            
        except Exception as e:
            db.rollback()
            print(f"初始化数据库失败: {e}")
            raise
        finally:
            db.close()
            
    except Exception as e:
        print(f"数据库初始化过程中发生错误: {e}")
        raise

def create_sample_product_data(db):
    # 检查是否已有数据
    existing_data = db.query(DBProduct).first()
    if existing_data:
        print("商品数据已存在，跳过示例数据创建")
        return
    
    print("创建示例商品数据...")
    import random
    
    categories = ["电子产品", "服装", "食品", "家居", "图书"]
    products = {
        "电子产品": ["手机", "笔记本电脑", "耳机", "智能手表"],
        "服装": ["T恤", "牛仔裤", "外套", "连衣裙"],
        "食品": ["巧克力", "饼干", "咖啡", "坚果"],
        "家居": ["台灯", "椅子", "床单", "餐具"],
        "图书": ["小说", "技术书籍", "杂志", "儿童读物"]
    }
    
    total_records = 0
    
    for category in categories:
        for product_name in products[category]:
            # 创建商品
            product = DBProduct(
                product_name=product_name,
                price=round(random.uniform(10.0, 500.0), 2),
                category=category,
                stock=random.randint(10, 100),
                sales=random.randint(0, 50)
            )
            db.add(product)
            total_records += 1
    
    try:
        db.commit()
        print(f"示例商品数据创建成功！共创建 {total_records} 条记录")
    except Exception as e:
        db.rollback()
        print(f"创建示例数据失败: {e}")
        raise

if __name__ == "__main__":
    init_db()
    print("数据库初始化完成")